package team.paimengshop.show;

import javafx.beans.property.SimpleDoubleProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.AnchorPane;
import javafx.scene.text.Font;
import javafx.stage.FileChooser;
import team.paimengshop.server_database.CommodityInfoOperate;
import team.paimengshop.server_dataclass.Commodity;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Objects;
import java.util.ResourceBundle;

public class shelvesController implements Initializable
{
    private final TableView<Good> table = new TableView<>();
    private final ObservableList<Good> data =
            FXCollections.observableArrayList();

    @FXML
    private Button selectButton;

    @FXML
    private AnchorPane shelvesPane;

    @FXML
    private Button upBtn;

    @FXML
    private Button offBtn;

    @FXML
    private TextField deleteInput;

    @FXML
    private TextField commodityNameInput;

    @FXML
    private TextField imgFilePathInput;

    @FXML
    private TextField productIntroInput;

    @FXML
    private TextField priceInput;

    @FXML
    private TextField textInput1;

    @FXML
    private TextField textInput2;

    @FXML
    private Button button1;

    @FXML
    private Button button2;

    private TableColumn idCol;

    private TableColumn commodityNameCol;

    private TableColumn priceCol;

    private TableColumn productIntroCol;

    private TableColumn imgFilePathCol;

    ArrayList<Commodity> commodityArrayList;

    private ArrayList<Integer> idList;

    private ArrayList<String> nameList;


    @Override
    public void initialize(URL url, ResourceBundle resourceBundle)
    {
        commodityArrayList = CommodityInfoOperate.GetAllCommodity();
        for(int i = 0; i < commodityArrayList.size(); i++)
        {
            Commodity commodity = commodityArrayList.get(i);
            Good good = new Good(commodity.getId(), commodity.getName(), commodity.getPrice(), commodity.getIntroduction(), commodity.getImageURL());
            data.add(good);
        }

        shelvesPane.getStylesheets().add(getClass().getResource("All.css").toExternalForm());

        table.setEditable(true);

        idCol = new TableColumn("Id");
        idCol.setPrefWidth(80);
        idCol.setMinWidth(50);
        idCol.setCellValueFactory(
                new PropertyValueFactory<>("id"));

        commodityNameCol = new TableColumn("commodityName");
        commodityNameCol.setPrefWidth(250);
        commodityNameCol.setMinWidth(50);
        commodityNameCol.setCellValueFactory(
                new PropertyValueFactory<>("commodityName"));
        commodityNameCol.setSortable(false);

        priceCol = new TableColumn("price");
        priceCol.setPrefWidth(100);
        priceCol.setMinWidth(50);
        priceCol.setCellValueFactory(
                new PropertyValueFactory<>("price"));

        productIntroCol = new TableColumn("productIntro");
        productIntroCol.setPrefWidth(250);
        productIntroCol.setMinWidth(50);
        productIntroCol.setCellValueFactory(
                new PropertyValueFactory<>("productIntro"));
        productIntroCol.setSortable(false);

        imgFilePathCol = new TableColumn("imgFilePath");
        imgFilePathCol.setPrefWidth(500);
        imgFilePathCol.setMinWidth(50);
        imgFilePathCol.setCellValueFactory(
                new PropertyValueFactory<>("imgFilePath"));
        imgFilePathCol.setSortable(false);


        table.setPrefWidth(1200);
        table.setPrefHeight(450);
        table.setItems(data);
        table.getColumns().addAll(idCol, commodityNameCol, priceCol,productIntroCol,imgFilePathCol);

        shelvesPane.getChildren().add(table);

        commodityNameInput.setPromptText("商品名称");
        priceInput.setPromptText("价格");
        imgFilePathInput.setPromptText("图片名");
        productIntroInput.setPromptText("商品简介");
        deleteInput.setPromptText("请输入要删除商品的ID");

        commodityNameInput.getStyleClass().add("input-group-special");
        priceInput.getStyleClass().add("input-group-special");
        imgFilePathInput.getStyleClass().add("input-group-special");
        productIntroInput.getStyleClass().add("input-group-special");
        deleteInput.getStyleClass().add("input-group-special");

        upBtn.getStyleClass().add("button-transparent-special-forImgBtn");
        offBtn.getStyleClass().add("button-transparent-special-forImgBtn");

        Image img1 = new Image("file:PaiMengShop/PaiMengShopServer/src/main/resources/team/paimengshop/show/image/up.png");
        Image img2 = new Image("file:PaiMengShop/PaiMengShopServer/src/main/resources/team/paimengshop/show/image/off.png");
        ImageView imageView1 = new ImageView(img1);
        ImageView imageView2 = new ImageView(img2);

        upBtn.setGraphic(imageView1);
        offBtn.setGraphic(imageView2);

        imgFilePathInput.setDisable(true);

        idList = new ArrayList<>();
        for(int i = 0; i < commodityArrayList.size(); i++)
        {
            idList.add((Integer)idCol.getCellData(i));
        }
        nameList = new ArrayList<>();
        for(int i = 0; i < commodityArrayList.size(); i++)
        {
            nameList.add((String)commodityNameCol.getCellData(i));
        }
    }
    @FXML
    void OnupBtnClicked(ActionEvent event)  //上架商品
    {
        if(Objects.equals(commodityNameInput.getText(), "")||Objects.equals(priceInput.getText(), "")||Objects.equals(imgFilePathInput.getText(), "")||Objects.equals(productIntroInput.getText(), ""))
        {
            Alert alert =new Alert(Alert.AlertType.INFORMATION);
            alert.setTitle("上架商品");
            alert.setContentText("请输入完整的商品信息");
            alert.setHeaderText("注意");
            alert.showAndWait();
        }
        else
        {
            Good good = data.get(data.size() - 1);
            data.add(new Good(good.getId() + 1,commodityNameInput.getText(),Double.parseDouble(priceInput.getText()),productIntroInput.getText(),imgFilePathInput.getText()));
            CommodityInfoOperate.Add(commodityNameInput.getText(), productIntroInput.getText(), imgFilePathInput.getText(), Double.parseDouble(priceInput.getText()));
            commodityNameInput.clear();
            imgFilePathInput.clear();
            productIntroInput.clear();
            priceInput.clear();
        }
    }

    @FXML
    void OnoffBtnCLicked(ActionEvent event)  //下架商品
    {
        if(Objects.equals(deleteInput.getText(), ""))
        {
            Alert alert =new Alert(Alert.AlertType.INFORMATION);
            alert.setTitle("上架商品");
            alert.setContentText("请输入商品ID");
            alert.setHeaderText("注意");
            alert.showAndWait();
        }
        else if (!checkID(Integer.parseInt(deleteInput.getText())))
        {
            Alert alert =new Alert(Alert.AlertType.INFORMATION);
            alert.setTitle("上架商品");
            alert.setContentText("当前商品列表中没有此ID");
            alert.setHeaderText("注意");
            alert.showAndWait();
        }
        else
        {
            int id = Integer.parseInt(deleteInput.getText());
            for(int i=0;i<data.size();i++)
            {
                if(data.get(i).getId()==id)
                    data.remove(i);
            }
            CommodityInfoOperate.DeleteById(id);
            deleteInput.clear();

        }
    }

    public static void configureFileChooser(FileChooser fileChooser)
    {
        fileChooser.setTitle("打开图片");
        fileChooser.setInitialDirectory(new File(System.getProperty("user.home")));
        fileChooser.getExtensionFilters().addAll(
                new FileChooser.ExtensionFilter("JPG图片", "*.jpg"),
                new FileChooser.ExtensionFilter("PNG图片", "*.png")
        );
    }

    @FXML
    void SelectButtonClicked(ActionEvent event)
    {
        FileChooser fileChooser = new FileChooser();
        configureFileChooser(fileChooser);
        File file = fileChooser.showOpenDialog(null);
        if (file != null)
        {
            String path = "PaiMengShop\\PaiMengShopServer\\src\\main\\resources\\team\\paimengshop\\show\\commodityImage\\" + file.getName();
            File copyFile = null;
            try
            {
                copyFile = new File(path);
                Files.copy(file.toPath(), copyFile.toPath());
                imgFilePathInput.setText("file:" + path.replaceAll("\\\\", "/"));
            } catch (FileAlreadyExistsException e)
            {
                Alert alert =new Alert(Alert.AlertType.INFORMATION);
                alert.setTitle("选择图片");
                alert.setContentText("该图片已存在，请选取其他图片");
                alert.setHeaderText("图片已存在");
                alert.showAndWait();
            } catch (IOException e)
            {
                e.printStackTrace();
            }

        }
    }

    boolean checkID(int id)
    {
        for(int i=0;i<data.size();i++)
        {
            if(data.get(i).getId()==id)
                return true;   //表示已有该ID
        }
        return false;   //表示没有该ID
    }

    public void Button1Clicked(ActionEvent actionEvent)
    {
        if(textInput1.getText().equals("") || textInput1.getText() == null)
        {
            Alert alert = new Alert(Alert.AlertType.INFORMATION);
            alert.setTitle("查询");
            alert.setContentText("商品id不能为空！");
            alert.setHeaderText("查询失败");
            alert.showAndWait();
        }
        else
        {
            idCol.setSortType(TableColumn.SortType.ASCENDING);
            table.requestFocus();
            int index;
            try
            {
                index = BinarySearch(idList, Integer.parseInt(textInput1.getText()));
            }
            catch (NumberFormatException e)
            {
                index = -1;
            }
            if(index != -1)
            {
                table.getSelectionModel().select(index);
                table.scrollTo(index);
                textInput1.clear();
            }
            else
            {
                Alert alert = new Alert(Alert.AlertType.INFORMATION);
                alert.setTitle("查询");
                alert.setContentText("商品id不存在！");
                alert.setHeaderText("查询失败");
                alert.showAndWait();
                textInput1.clear();
            }
        }
    }

    public void Button2Clicked(ActionEvent actionEvent)
    {
        if(textInput2.getText().equals("") || textInput2.getText() == null)
        {
            Alert alert = new Alert(Alert.AlertType.INFORMATION);
            alert.setTitle("查询");
            alert.setContentText("商品名称不能为空！");
            alert.setHeaderText("查询失败");
            alert.showAndWait();
        }
        else
        {
            idCol.setSortType(TableColumn.SortType.ASCENDING);
            table.requestFocus();
            int index = -1;
            for(int i = 0; i < nameList.size(); i++)
            {
                if(nameList.get(i).equals(textInput2.getText()))
                {
                    index = i;
                    break;
                }
            }
            if(index != -1)
            {
                table.getSelectionModel().select(index);
                table.scrollTo(index);
                textInput2.clear();
            }
            else
            {
                Alert alert = new Alert(Alert.AlertType.INFORMATION);
                alert.setTitle("查询");
                alert.setContentText("商品名称不存在！");
                alert.setHeaderText("查询失败");
                alert.showAndWait();
                textInput2.clear();
            }
        }
    }

    public void Refresh(ActionEvent actionEvent)
    {
        data.clear();
        table.refresh();
        commodityArrayList.clear();
        commodityArrayList = CommodityInfoOperate.GetAllCommodity();
        for(int i = 0; i < commodityArrayList.size(); i++)
        {
            Commodity commodity = commodityArrayList.get(i);
            Good good = new Good(commodity.getId(), commodity.getName(), commodity.getPrice(), commodity.getIntroduction(), commodity.getImageURL());
            data.add(good);
        }

        shelvesPane.getStylesheets().add(getClass().getResource("All.css").toExternalForm());

        table.setEditable(true);

        idCol = new TableColumn("Id");
        idCol.setPrefWidth(80);
        idCol.setMinWidth(50);
        idCol.setCellValueFactory(
                new PropertyValueFactory<>("id"));

        commodityNameCol = new TableColumn("commodityName");
        commodityNameCol.setPrefWidth(250);
        commodityNameCol.setMinWidth(50);
        commodityNameCol.setCellValueFactory(
                new PropertyValueFactory<>("commodityName"));
        commodityNameCol.setSortable(false);

        priceCol = new TableColumn("price");
        priceCol.setPrefWidth(100);
        priceCol.setMinWidth(50);
        priceCol.setCellValueFactory(
                new PropertyValueFactory<>("price"));

        productIntroCol = new TableColumn("productIntro");
        productIntroCol.setPrefWidth(250);
        productIntroCol.setMinWidth(50);
        productIntroCol.setCellValueFactory(
                new PropertyValueFactory<>("productIntro"));
        productIntroCol.setSortable(false);

        imgFilePathCol = new TableColumn("imgFilePath");
        imgFilePathCol.setPrefWidth(500);
        imgFilePathCol.setMinWidth(50);
        imgFilePathCol.setCellValueFactory(
                new PropertyValueFactory<>("imgFilePath"));
        imgFilePathCol.setSortable(false);


        table.setPrefWidth(1200);
        table.setPrefHeight(450);
        table.setItems(data);
        table.getColumns().addAll(idCol, commodityNameCol, priceCol,productIntroCol,imgFilePathCol);

        commodityNameInput.setPromptText("商品名称");
        priceInput.setPromptText("价格");
        imgFilePathInput.setPromptText("图片名");
        productIntroInput.setPromptText("商品简介");
        deleteInput.setPromptText("请输入要删除商品的ID");

        commodityNameInput.getStyleClass().add("input-group-special");
        priceInput.getStyleClass().add("input-group-special");
        imgFilePathInput.getStyleClass().add("input-group-special");
        productIntroInput.getStyleClass().add("input-group-special");
        deleteInput.getStyleClass().add("input-group-special");

        upBtn.getStyleClass().add("button-transparent-special-forImgBtn");
        offBtn.getStyleClass().add("button-transparent-special-forImgBtn");

        Image img1 = new Image("file:PaiMengShop/PaiMengShopServer/src/main/resources/team/paimengshop/show/image/up.png");
        Image img2 = new Image("file:PaiMengShop/PaiMengShopServer/src/main/resources/team/paimengshop/show/image/off.png");
        ImageView imageView1 = new ImageView(img1);
        ImageView imageView2 = new ImageView(img2);

        upBtn.setGraphic(imageView1);
        offBtn.setGraphic(imageView2);

        imgFilePathInput.setDisable(true);

        idList = new ArrayList<>();
        for(int i = 0; i < commodityArrayList.size(); i++)
        {
            idList.add((Integer)idCol.getCellData(i));
        }
        nameList = new ArrayList<>();
        for(int i = 0; i < commodityArrayList.size(); i++)
        {
            nameList.add((String)commodityNameCol.getCellData(i));
        }
    }

    public static class Good//商品数据模板，用于绑定表格中的单元
    {
        private final SimpleIntegerProperty id;
        private final SimpleStringProperty commodityName;
        private final SimpleDoubleProperty price;
        private final SimpleStringProperty productIntro;
        private final SimpleStringProperty imgFilePath;


        private Good(int id, String commodityName, double price, String productIntro, String imgFilePath)

        {
            this.id = new SimpleIntegerProperty(id);
            this.commodityName = new SimpleStringProperty(commodityName);
            this.price = new SimpleDoubleProperty(price);
            this.productIntro = new SimpleStringProperty(productIntro);
            this.imgFilePath = new SimpleStringProperty(imgFilePath);
        }

        public int getId() {
            return id.get();
        }

        public SimpleIntegerProperty idProperty() {
            return id;
        }

        public void setId(int id) {
            this.id.set(id);
        }

        public String getCommodityName() {
            return commodityName.get();
        }

        public SimpleStringProperty commodityNameProperty() {
            return commodityName;
        }

        public void setCommodityName(String commodityName) {
            this.commodityName.set(commodityName);
        }

        public double getPrice() {
            return price.get();
        }

        public SimpleDoubleProperty priceProperty() {
            return price;
        }

        public void setPrice(double price) {
            this.price.set(price);
        }

        public String getProductIntro() {
            return productIntro.get();
        }

        public SimpleStringProperty productIntroProperty() {
            return productIntro;
        }

        public void setProductIntro(String productIntro) {
            this.productIntro.set(productIntro);
        }

        public String getImgFilePath() {
            return imgFilePath.get();
        }

        public SimpleStringProperty imgFilePathProperty() {
            return imgFilePath;
        }

        public void setImgFilePath(String imgFilePath) {
            this.imgFilePath.set(imgFilePath);
        }
    }

    public static int BinarySearch(ArrayList<Integer> idList, int id)
    {
        int begin = 0;
        int end = idList.size() - 1;
        while(begin <= end)
        {
            int mid = (begin + end) / 2;
            if(idList.get(mid) > id)
            {
                end = mid - 1;
            }
            else if(idList.get(mid) < id)
            {
                begin = mid + 1;
            }
            else
            {
                return mid;
            }
        }
        return -1;
    }
}